<?php

namespace app\library;

class ClientInfo
{
    /**
     * cookie key
     */
    const COOKIE_KEY_ID = 'hcl_cid';
    /**
     * @var self
     */
    private static $_self;

    /**
     * 获取当前实例
     * @return self
     */
    public static function instance()
    {
        if (static::$_self == null) {
            static::$_self = new static;
        }
        return static::$_self;
    }

    /**
     * 生成GUID
     * @return string GUID STRING
     */
    public function guid()
    {
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {
            mt_srand((double)microtime() * 10000);//optional for php 4.2.0 and up.
            $charid = strtoupper(md5(uniqid(rand(), true)));
            $hyphen = chr(45);
            $uuid = chr(123)
                . substr($charid, 0, 8) . $hyphen
                . substr($charid, 8, 4) . $hyphen
                . substr($charid, 12, 4) . $hyphen
                . substr($charid, 16, 4) . $hyphen
                . substr($charid, 20, 12)
                . chr(125);
            return $uuid;
        }
    }

    /**
     * 获取客户端ID
     * @return string
     */
    public function getClientId()
    {
        $cid = isset($_COOKIE[static::COOKIE_KEY_ID]) ? $_COOKIE[static::COOKIE_KEY_ID] : null;
        if ($cid != null && empty($cid) == false) {
            return $cid;
        }
        $cid = md5($this->guid() . time());
        $domain = defined('WEB_DOMAIN') ? WEB_DOMAIN : null;
        // 存明文
        setcookie(static::COOKIE_KEY_ID, $cid, time() + (3600 * 24 * 365 * 10), '/', $domain);
        return $cid;
    }
}